package com.joker.service.impl;

import com.joker.Exception.NotFoundException;
import com.joker.dao.TagRepository;
import com.joker.pojo.Tag;
import com.joker.pojo.Type;
import com.joker.service.TagService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;

import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;


/**
 * @Author JokerKS
 * @Date 2021/12/06 15:39
 * @Version 1.0
 */
@Service
public class TagServiceImpl implements TagService {

	@Autowired
	private TagRepository tagRepository;

	@Transactional
	@Override
	public Tag saveTag(Tag tag) {
		return tagRepository.save(tag);
	}

	@Transactional
	@Override
	public Tag getTag(Long id) {
		return tagRepository.findById(id).get();
	}

	@Override
	public Tag getTagByName(String name) {
		return tagRepository.findByName(name);
	}

	@Override
	public Page<Tag> listTag(Pageable pageable) {
		return tagRepository.findAll(pageable);
	}

	@Override
	public List<Tag> listTag() {
		return tagRepository.findAll();
	}

	@Override
	public List<Tag> listTag(String ids) {
		return tagRepository.findAllById(convertToList(ids));
	}

	//将字符串转换成数组
	private List<Long> convertToList(String ids) {
		List<Long> list = new ArrayList<>();
		if (!"".equals(ids) && ids != null) {
			String[] idarray = ids.split(",");
			for (int i = 0; i < idarray.length; i++) {
				list.add(new Long(idarray[i]));
			}
		}
		return list;
	}

	@Override
	public List<Tag> listTagTop(Integer size) {
		Sort sort = Sort.by(Sort.Direction.DESC, "blogs.size");
		Pageable pageable = PageRequest.of(0, size, sort);
		return tagRepository.findTop(pageable);
	}


	@Override
	public Tag updateTag(Long id, Tag tag) {
		Tag t = tagRepository.findById(id).get();
		if (t == null) {
			throw new NotFoundException("不存在该标签");
		}
		BeanUtils.copyProperties(tag, t);

		return tagRepository.save(t);
	}

	@Override
	public void deleteTag(Long id) {
		tagRepository.deleteById(id);
	}
}
